﻿using System.Collections.Generic;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class SqRefU
    {
        private readonly List<Ref8U> Ref8Us = new List<Ref8U>();

        public void Read(BinaryReader reader)
        {
            ushort cref = reader.ReadUInt16();
            for (int i = 0; i < cref; i++)
            {
                var ref8U = new Ref8U();
                ref8U.Read(reader);
                Ref8Us.Add(ref8U);
            }
        }

        public Range ToRange(Worksheet worksheet)
        {
            var ranges = new List<SimpleRange>();
            foreach (Ref8U v in Ref8Us)
                ranges.Add(CellsRange.Create(worksheet, (RangeAddress) v));
            if (ranges.Count == 1)
                return ranges[0];
            return new CompositeRange(ranges);
        }
        public static SqRefU FromRangeAddress (IEnumerable<RangeAddress> addresses)
        {
            SqRefU result = new SqRefU();
            foreach (var rangeAddress in addresses)
            {
                result.Ref8Us.Add((Ref8U) rangeAddress);
            }
            return result;
        }
        public static SqRefU FromRange (Range range)
        {
            return FromRangeAddress(Enumerable.Select(range.GetSimpleRanges(), r => r.Address));
        }

        public void Write(BinaryWriter writer)
        {
            ushort cref = (ushort) this.Ref8Us.Count;
            writer.Write(cref);
            foreach (var r in this.Ref8Us)
                r.Write(writer);
        }
    }
}